package BuyerAgent;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import Ontologies.TreeWithPrice;

/**
 * This class is the GUI for buyer agent, that facilitates the operations of
 * user in changing the wish list and start the buyer agent
 * 
 * @author DUY HAN PHAN
 * 
 */
public class BuyerGUI extends JFrame {

	private JPanel contentPane;
	private JTextField txtQuantity;
	private final JSeparator separator = new JSeparator();
	public volatile JTable table;
	private Buyer buyerAgent;
	private Map<String, java.util.List<TreeWithPrice>> trees;
	JComboBox comboBoxCategory;
	JComboBox comboBoxTree;

	/**
	 * Create the frame.
	 */
	public BuyerGUI(Buyer buyerAgentInstance) {
		this.buyerAgent = buyerAgentInstance;

		setTitle(buyerAgent.agentLocalName);

		initializeTreesData();

		setResizable(false);
		// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 651, 520);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JLabel lblCategory = new JLabel("Category");
		lblCategory.setBounds(10, 11, 74, 14);
		contentPane.add(lblCategory);

		comboBoxCategory = new JComboBox();
		comboBoxCategory.setMaximumRowCount(20);
		comboBoxCategory.setBounds(80, 6, 161, 25);
		contentPane.add(comboBoxCategory);

		JLabel lblTree = new JLabel("Tree");
		lblTree.setBounds(259, 10, 55, 16);
		contentPane.add(lblTree);

		comboBoxTree = new JComboBox();
		comboBoxTree.setBounds(301, 6, 186, 25);
		contentPane.add(comboBoxTree);

		JLabel lblQuantity = new JLabel("Quantity");
		lblQuantity.setBounds(505, 10, 55, 16);
		contentPane.add(lblQuantity);

		txtQuantity = new JTextField();
		txtQuantity.setBounds(578, 8, 55, 20);
		contentPane.add(txtQuantity);
		txtQuantity.setColumns(10);

		JButton btnAddtowishlist = new JButton("AddToWishList");
		btnAddtowishlist.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				int quantity = 0;
				boolean isShowMsg = false;
				try {
					quantity = Integer.parseInt(txtQuantity.getText());
				} catch (Exception e) {
					e.printStackTrace();
					// handling the wrong input from users
					isShowMsg = true;
					JOptionPane.showMessageDialog(null, "Please input a number greater than 1", "InfoBox",
							JOptionPane.ERROR_MESSAGE);
					return;
				}
				if (quantity < 1 && isShowMsg == false) {
					JOptionPane.showMessageDialog(null, "Please input a number greater than 1", "InfoBox",
							JOptionPane.ERROR_MESSAGE);
					return;
				}
				String commonName = comboBoxTree.getSelectedItem().toString();
				String category = comboBoxCategory.getSelectedItem().toString();
				String latinName = getLatinNameFromCommonName(category, commonName);
				if (latinName == null) {
					latinName = "";
				}
				Tree tree = new Tree(commonName, latinName, category, quantity);
				buyerAgent.wishList.add(tree);
				// TODO show wish list table
				WishListModelTable wishListModelTable = new WishListModelTable(buyerAgent.wishList);
				table.setModel(wishListModelTable);
				table.updateUI();

			}
		});
		btnAddtowishlist.setBounds(249, 60, 143, 26);
		contentPane.add(btnAddtowishlist);
		separator.setBounds(0, 100, 645, 14);
		contentPane.add(separator);

		JLabel lblWishList = new JLabel("Wish List");
		lblWishList.setBounds(10, 111, 55, 16);
		contentPane.add(lblWishList);

		JButton btnRemove = new JButton("Remove");
		btnRemove.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				WishListModelTable tableModel = (WishListModelTable) table.getModel();
				buyerAgent.wishList.remove(table.getSelectedRow());
				tableModel.removeRow(table.getSelectedRow());
				table.updateUI();
			}
		});
		btnRemove.setBounds(10, 454, 98, 26);
		contentPane.add(btnRemove);

		JButton btnSave = new JButton("Save");
		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				// TODO save wish list to file
				buyerAgent.saveWishListToFile();
				JOptionPane.showMessageDialog(null, "Current wish list has been saved to file", "InfoBox",
						JOptionPane.INFORMATION_MESSAGE);
			}
		});
		btnSave.setBounds(280, 454, 98, 26);
		contentPane.add(btnSave);

		JButton btnStart = new JButton("Start");
		btnStart.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(buyerAgent.wishList.size() < 1) {
					JOptionPane.showMessageDialog(null, "Wish list is empty, Please add some trees", "InfoBox",
							JOptionPane.ERROR_MESSAGE);
					return;
				}
				buyerAgent.addBehaviour(buyerAgent.purchaseTransactionBehaviour);
				// buyerAgent.addBehaviour(new
				// GetMainContainerLocationBehaviour(buyerAgent));
			}
		});
		btnStart.setBounds(535, 454, 98, 26);
		contentPane.add(btnStart);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 139, 623, 303);
		contentPane.add(scrollPane);

		table = new JTable();
		scrollPane.setViewportView(table);

		this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

		comboBoxCategory.addItemListener(new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent e) {
				if (e.getStateChange() == ItemEvent.SELECTED) {
					comboBoxTree.removeAllItems();
					for (TreeWithPrice tree : trees.get((String) comboBoxCategory.getSelectedItem())) {
						comboBoxTree.addItem(tree.getCommonName());
					}
				}
			}
		});

		comboBoxTree.addItemListener(new ItemListener() {
			@Override
			public void itemStateChanged(ItemEvent e) {
				if (e.getStateChange() == ItemEvent.SELECTED) {
					// DONOTHING
				}
			}
		});

		initializeGUIData();

		// addWindowListener(new WindowAdapter() {
		// public void windowClosing(WindowEvent e) {
		// buyerAgent.doDelete();
		// }
		// });
	}

	/**
	 * Get all trees list
	 */
	private void initializeTreesData() {
		trees = new HashMap<String, List<TreeWithPrice>>();
		if (buyerAgent instanceof Buyer) {
			for (TreeWithPrice tree : buyerAgent.allTreesList) {
				String category = tree.getCategory();
				if (trees.containsKey(category)) {
					trees.get(category).add(tree);
				} else {
					List<TreeWithPrice> list = new ArrayList<TreeWithPrice>();
					list.add(tree);
					trees.put(category, list);
				}
			}
		}
	}

	/**
	 * Populate all trees list to GUI
	 */
	private void initializeGUIData() {
		for (String string : trees.keySet()) {
			comboBoxCategory.addItem(string);
		}
		comboBoxTree.removeAllItems();
		for (TreeWithPrice tree : trees.get((String) comboBoxCategory.getSelectedItem())) {
			comboBoxTree.addItem(tree.getCommonName());
		}
	}

	/**
	 * @param category
	 * @param commonName
	 * @return
	 */
	private String getLatinNameFromCommonName(String category, String commonName) {
		String latinName = null;
		List<TreeWithPrice> allTreesInCategory = trees.get(category);
		for (int i = 0; i < allTreesInCategory.size(); i++) {
			if (allTreesInCategory.get(i).getCommonName().equals(commonName)) {
				latinName = allTreesInCategory.get(i).getLatinName();
				break;
			}
		}
		return latinName;
	}
}
